package com.sojson.config.qps.sentinel.origin;

import java.io.IOException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import com.sojson.util.agent.UserAgentUtil;
import com.sojson.util.param.ParamUtil;
import com.sojson.util.servlet.ServletUtil;
import com.sojson.util.token.Token;
import com.sojson.util.token.TokenUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 配置请求来源
 * 
 * @author liu
 * @date 2021-08-25
 */
@Slf4j
@Configuration
public class CustomRequestOriginParser {

    /**
     * 获取来源信息</BR>
     * CommonFilter在获取entry之前会使用RequestOriginParser从request中解析来源</BR>
     * 
     * @return
     */
    @Bean
    public RequestOriginParser parseOrigin() {
        return (request -> {
            String origin = null;
            try {
                Token token = TokenUtil.getToken();
                if (ParamUtil.isLogin(token)) {
                    origin = token.getUser().getId();
                } else {
                    String remoteAddr = ServletUtil.getTargetIp(request);
                    String userAgent = request.getHeader(UserAgentUtil.USER_AGENT_KEY);
                    origin =
                        String.join("|", (remoteAddr == null ? "" : remoteAddr), (userAgent == null ? "" : userAgent));
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            return origin;
        });
    }

}